package a_doubleWrite;

/**
 * 130. 被围绕的区域
 * 给你一个 m x n 的矩阵 board ，由若干字符 'X' 和 'O' ，找到所有被 'X' 围绕的区域，
 * 并将这些区域里所有的 'O' 用 'X' 填充。
 * @author luolidong
 * @version 1.0
 * @create 2021-07-26 11:48
 */
public class L130 {
    int iLen;
    int jLen;
    public void solve(char[][] board) {
        iLen=board.length;
        jLen=board[0].length;
        for (int i = 0; i <jLen ; i++) {
            dfs(board,0,i);
            dfs(board,iLen-1,i);
        }
        for (int i = 1; i <iLen-1 ; i++) {
            dfs(board,i,0);
            dfs(board,i,jLen-1);
        }
        for (int i = 0; i <iLen ; i++) {
            for (int j = 0; j <jLen ; j++) {
                if(board[i][j]=='O'){
                    board[i][j]='X';
                }
                if(board[i][j]=='#'){
                    board[i][j]='O';
                }
            }
        }
    }

    private void dfs(char[][] board, int i, int j) {
        if(i<0||i>=iLen||j<0||j>=jLen||board[i][j]!='O'){
            return;
        }
        board[i][j]='#';
        dfs(board, i-1, j);
        dfs(board, i+1, j);
        dfs(board, i, j+1);
        dfs(board, i, j-1);
    }
}
